<?php
namespace Manage\Controller;
use Think\Controller;

/**
 * Class MobileController
 * @package Manage\Controller
 * 手机端所有请求
 */
class MobileController extends Controller {

    private $session_module = 'MobileAdmin';

    public function index(){

    }

    public function login(){
        $this->display();
    }

    /**
     * @return bool检查登录
     */
    public function check_login(){
        $uid = I('get.uid')?I('get.uid'):false;
        if(!$uid){
            echo json_encode(array('status'=>-999, 'msg'=>'plz login'));
            exit();
        }
    }

    public function login_action(){
        $username = I('post.username')?I('post.username'):I('get.username');
        $pwd = I('post.password')?I('post.password'):I('get.password');
        $user = M('MobileAdmin');
        $where['username'] =array('eq', $username);
        $where['password'] = array('eq', $pwd);
        $useryesornot =  $user->where($where)->find();
        $user_status = D('MobileRegest')->find_last_one_by_user($useryesornot['id']);
        if($this->last_is_work($user_status)){
            $user_status = 2;
        }else{
            $user_status = 1;
        }
        if($useryesornot){
            //设置用户名缓存
            $fyls = $this->query_station_mac_gate($useryesornot['id']);
            //登录成功
            echo json_encode(array('status'=>1, 'msg'=>'登录成功','realname'=>$useryesornot['realname']
            , 'uid'=>$useryesornot['id'], 'stations' => $fyls['stations'],'csdts' => $fyls['csdts'],'gates' => $fyls['gates'], 'work_status'=>$user_status));
        }else{
            echo json_encode(array('status'=>-1, 'msg'=>'用户名和密码错误','username'=>$username,'password'=>$pwd));
        }
    }

    public function logout(){
        destory_module_session($this->session_module);
        echo json_encode(array('status'=>0, 'msg'=>'成功退出'));
    }

    private function sign($photo, $gps, $address, $uid){
        $this->check_login();
        $data = array();
        $data['photo'] = $photo;
        $data['point'] = $gps;
        $data['address'] = $address;
        $model = D('MobileRegest');
        $data['uid'] = $uid;
        $data['time'] = time();
        $start_work_rang = explode(',', get_kv_val('start_work_rang'));
        $end_work_rang = explode(',', get_kv_val('end_work_rang'));
        $now_hour = date('H');
        $user_status = $model->find_last_one_by_user($data['uid']);
        if($this->last_is_work($user_status)){
            //前面一条是上班，只有下班和早退
//            if($now_hour<$end_work_rang[0]){
//                //到点前下班是早退，过了点下班时正常
//                $data['status'] = -2;
//            }else{
//                $data['status'] = 2;
//            }
            $data['status'] = 2;
            //记录下班时间
            set_module_session($this->session_module, 'off_duty_time', time());
        }else{
            //前面一条是下班，只有上班和迟到
//            if($now_hour>$start_work_rang[1]){
//                $data['status'] = -1;
//            }else{
//                $data['status'] = 1;
//            }
            //交接班超过20分钟，视为迟到
            $time_gap = get_kv_val('liuzhen_gap')?get_kv_val('liuzhen_gap'):20;
            if(!get_module_session($this->session_module, 'off_duty_time')){
                //默认session有效时间为24分钟
                $data['status'] = -1;
            }else if(time() - get_module_session($this->session_module, 'off_duty_time') > $time_gap*60){
                $data['status'] = -1;
            }else{
                $data['status'] = 1;
            }
        }
        $data['signposition'] = $this->get_fly_names($data['uid']);
        $one = $model->addObj($data);
        $user_status = $model->find_last_one_by_user($data['uid']);
        if($one){
            if($this->last_is_work($user_status)){
                return json_encode(array('status'=>2, 'msg'=>'下班'));
            }else{
                return json_encode(array('status'=>1, 'msg'=>'下班'));
            }
        }else
            return json_encode(array('status'=>-1, 'msg'=>'打卡失败'));
    }

    public function get_sign_status(){
        $this->check_login();
        $model = D('MobileRegest');
        $uid = I('get.uid')?I('get.uid'):0;
        $user_status = $model->find_last_one_by_user($uid);
        if($this->last_is_work($user_status)){
            echo json_encode(array('status'=>2, 'msg'=>'下班'));
        }else{
            echo json_encode(array('status'=>1, 'msg'=>'上班'));
        }
    }

    /**
     * @param $status
     * 上一条是上班
     */
    private function last_is_work($status){
        if($status==1||$status==-1)
            return true;
        else if($status==2||$status==-2)
            return false;
    }

    /**
     * 查询该用户的泵站、调蓄池、河道闸门
     */
    private function query_station_mac_gate($uid=0){
        $uid = ','.$uid.',';
        //查询泵站
        $station_model = D('PumpingStation');
        $stations = $station_model->query_ids_by_opr($uid);
        set_module_session($this->session_module, 'stations', $stations);
        //查询调蓄池
        $csdt_model = D('Csdt');
        $csdts = $csdt_model->query_ids_by_opr($uid);
        set_module_session($this->session_module, 'csdts', $csdts);
        //查询闸门
        $gate_model = D('Gate');
        $gates = $gate_model->query_ids_by_opr($uid);
        set_module_session($this->session_module, 'gates', $gates);
        return array('stations'=>implode(',', $stations),'csdts'=>implode(',', $csdts),'gates'=>implode(',', $gates),);
    }

    private function get_fly_names($uid){
        $str = '';
		$map = array();
        $map['ps_opr'] = array('like', '%,'.$uid.',%');
        //查询泵站
        $station_model = D('PumpingStation');
        $stations = $station_model->where($map)->select();
        foreach($stations as $station){
            $str .= $station['ps_name'].',';
        }
        //查询调蓄池
		$map = array();
        $map['ps_opr'] = array('like', '%,'.$uid.',%');
        $csdt_model = D('Csdt');
        $csdts = $csdt_model->where($map)->select();
        foreach($csdts as $csdt){
            $str .= $csdt['ps_name'].',';
        }
        //查询闸门
		$map = array();
        $map['gate_opr'] = array('like', '%,'.$uid.',%');
        $gate_model = D('Gate');
        $gates = $gate_model->where($map)->select();
        foreach($gates as $gate){
            $str .= $gate['gate_name'].',';
        }
        return $str;
    }

    public function main(){
        $this->check_login();
        $this->display();
    }

    /**
     * 文件上传，这里用作图片上传
     */
    public function uploadify()
    {
        if (!empty($_FILES)) {
            import("@.Think.UploadFile");
            $upload = new \Think\Upload();
            $upload->rootPath = C('UPLOAD_ROOT_PATH');
            $upload->savePath = date('Y').'/'.date('m').'/'.date('d').'/';
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->autoSub = false;
            $upload->saveRule = uniqid; //上传规则
            $info = $upload->upload();
            if (!$info) {
//                $this->error($upload->getError());//获取失败信息
                echo json_encode(array('status'=>-1, 'msg'=>$upload->getError()));
            } else {
                //成功
                $fileArray = "";
                foreach ($info as $file) {
                    $fileArray = '/'.C('UPLOAD_ROOT_PATH').$file['savepath'].$file['savename'];
                }
                $gps = I('get.gps')?I('get.gps'):'';
                $address = I('get.address')?I('get.address'):'';
                $uid = I('get.uid')?I('get.uid'):0;
                echo $this->sign($fileArray, $gps, $address, $uid);
            }

        }
    }

    /*******************************获取数据API*******************************/
    public function set_tab_enable(){
        $station = get_module_session($this->session_module, 'stations')?1:0;
        $csdt = get_module_session($this->session_module, 'csdts')?1:0;
        $gate = get_module_session($this->session_module, 'gates')?1:0;
        $station = I('get.stations')?1:0;
        $csdt = I('get.csdts')?1:0;
        $gate = I('get.gates')?1:0;
        $return_array['station'] = $station;
        $return_array['csdt'] = $csdt;
        $return_array['gate'] = $gate;
        echo json_encode($return_array);
    }
    /**
     * 泵机列表，根据model来判断是泵站还是调蓄池
     */
    public function get_pump(){
        $this->check_login();
        $model = I('get.model')?I('get.model'):false;
        if(!$model){
            echo json_encode(array('status'=>-1, 'msg'=>'pls put parm'));
            exit();
        }
        switch($model){
            case 'station':
                //泵站泵机
                $stations = I('get.stations')?explode(',',I('get.stations')):0;
                $pump_pump = D('PumpPump')->query_by_pids($stations, 'id,p_number,ps_id,p_auto');
                break;
            case 'csdt':
                $csdts = I('get.csdts')?explode(',',I('get.csdts')):0;
                $pump_pump = D('CsdtPump')->query_by_pids($csdts, 'id,p_number,ps_id,p_auto');
                break;
        }
        echo json_encode($pump_pump);
        unset($model);
        unset($pump_pump);
    }

    /**
     * 格栅机
     */
    public function get_machine(){
        $this->check_login();
        $model = I('get.model')?I('get.model'):false;
        if(!$model){
            echo json_encode(array('status'=>-1, 'msg'=>'pls put parm'));
            exit();
        }
        switch($model){
            case 'station':
                $stations = I('get.stations')?explode(',',I('get.stations')):0;
                $mac = D('PumpMachine')->query_by_pids($stations, 'id,scrmach_number,ps_id');
                break;
            case 'csdt':
                $csdts = I('get.csdts')?explode(',',I('get.csdts')):0;
                $mac = D('CsdtMachine')->query_by_pids($csdts, 'id,scrmach_number,ps_id');
                break;
        }
        echo json_encode($mac);
        unset($model);
        unset($mac);
    }

    /**
     *水电表
     */
    public function get_waterele(){
        $this->check_login();
        $model = I('get.model')?I('get.model'):false;
        if(!$model){
            echo json_encode(array('status'=>-1, 'msg'=>'pls put parm'));
            exit();
        }
        switch($model){
            case 'station':
                $stations = I('get.stations')?explode(',',I('get.stations')):0;
                $w = D('PumpWaterele')->query_by_pids($stations);
                break;
            case 'csdt':
                $csdts = I('get.csdts')?explode(',',I('get.csdts')):0;
                $w = D('CsdtWaterele')->query_by_pids($csdts);
                break;
        }
        echo json_encode($w);
        unset($model);
        unset($w);
    }

    public function get_water(){
        $this->check_login();
        $model = I('get.model')?I('get.model'):false;
        if(!$model){
            echo json_encode(array('status'=>-1, 'msg'=>'pls put parm'));
            exit();
        }
        switch($model){
            case 'station':
                $stations = I('get.stations')?explode(',',I('get.stations')):0;
                $w = D('PumpWater')->query_by_pids($stations);
                break;
            case 'csdt':
                $csdts = I('get.csdts')?explode(',',I('get.csdts')):0;
                $w = D('CsdtWater')->query_by_pids($csdts);
                break;
        }
        echo json_encode($w);
        unset($model);
        unset($w);
    }

    /**
     * 闸门
     */
    public function get_gate(){
        $this->check_login();
        $model = I('get.model')?I('get.model'):false;
        if(!$model){
            echo json_encode(array('status'=>-1, 'msg'=>'pls put parm'));
            exit();
        }
        switch($model){
            case 'gate':
                //泵站泵机
                $gates = I('get.gates')?explode(',',I('get.gates')):0;
                $gate = D('Gate')->query_by_pids($gates);
                break;
            case 'csdt':
                $csdts = I('get.csdts')?explode(',',I('get.csdts')):0;
                $gate = D('CsdtGate')->query_by_pids($csdts);
                break;
        }
        echo json_encode($gate);
        unset($model);
        unset($gate);
    }

    public function get_json_obj(){
        $this->check_login();
        $model = I('get.model')?I('get.model'):false;
        $id = I('get.id')?I('get.id'):false;
        if(!$model||!$id){
            echo json_encode(array('status'=>-1, 'msg'=>'pls put parm'));
            exit();
        }
        echo D($model)->get_json_obj($id);
    }

    /**
     * 数据提交的唯一接口，并且只做添加，不作修改
     */
    public function submit_action(){
        $this->check_login();
        $data = I('get.')?I('get.'):I('post.');
        $model = $data['model']?$data['model']:false;
        $id = $data['id']?$data['id']:false;
        if(!$model){
            echo json_encode(array('status'=>-1, 'msg'=>$data));
            exit();
        }
        $log_model = D($data['model'].'Record');
        $data['date'] = getNowTime();
        $data['opr'] = I('get.uid')?I('get.uid'):0;
        $data['status'] = ($data['status']!='')?$data['status']:-3;
        if($data['status'] == 1){
            //如果提交状态是开机，就直接保存
            $new_id = $log_model->addObj_mobile($data);
        }else if($data['status'] == 0 || $data['status'] == -2 || $data['status'] == -3){
            //如果是关机，看前一条是不是开机，是，更新前一条
            //如果是故障，看前一条是不是开机，是，更新前一条,不是，新增它
            switch($model){
                case 'PumpPump':
                    $new_id = $log_model->set_device_off($data['pumppumpid'], $data);
                    break;
                case 'PumpMachine':
                    $new_id = $log_model->set_device_off($data['macid'], $data);
                    break;
                case 'CsdtPump':
                    $new_id = $log_model->set_device_off($data['csdtpumpid'], $data);
                    break;
                case 'CsdtMachine':
                    $new_id = $log_model->set_device_off($data['macid'], $data);
                    break;
                case 'CsdtGate':
                    $new_id = $log_model->set_device_off($data['gateid'], $data);
                    break;
                case 'Gate':
                    $new_id = $log_model->set_device_off($data['gateid'], $data);
                    break;
                case 'PumpWaterele':
                    unset($data['status']);
                    $new_id = $log_model->addObj($data);
                    break;
                case 'CsdtWaterele':
                    unset($data['status']);
                    $new_id = $log_model->addObj($data);
                    break;
                case 'PumpWater':
                    unset($data['status']);
                    $new_id = $log_model->addObj($data);
                    break;
                case 'CsdtWater':
                    unset($data['status']);
                    $new_id = $log_model->addObj($data);
                    break;
            }
        }
//        else if(!$data['status']||!isset($data['status'])){
//            //水电表没有状态，所以直接保存
//            $new_id = $log_model->addObj($data);
//            if($new_id)
//                echo json_encode(array('status'=>$new_id, 'msg'=>'success'));
//            else
//                echo json_encode(array('status'=>-1, 'msg'=>'eooro'));
//        }
        if($new_id === false)
            echo json_encode(array('status'=>-1, 'msg'=>'保存失败'));
        else
            echo json_encode(array('status'=>$new_id, 'msg'=>'保存成功'));
        unset($data);
        unset($log_model);
    }

    public function get_facilities(){
        $this->check_login();
        $model = I('get.model')?I('get.model'):false;
        if(!$model){
            echo json_encode(array('status'=>-1, 'msg'=>'pls put parm'));
            exit();
        }
        switch($model){
            case 'station':
                $ids = I('get.stations')?explode(',',I('get.stations')):0;
                $ids = implode(',', $ids);
                if(!empty($ids))
                    $list = D('PumpingStation')->field('id,ps_name as name')->select($ids);
                else
                    $list = array();
                break;
            case 'csdt':
                $ids = I('get.csdts')?explode(',',I('get.csdts')):0;
                $ids = implode(',', $ids);
                if(!empty($ids))
                    $list = D('Csdt')->field('id,ps_name as name')->select($ids);
                else
                    $list = array();
                break;
            case 'gate':
                $ids = I('get.gates')?explode(',',I('get.gates')):0;
                $ids = implode(',', $ids);
                if(!empty($ids))
                    $list = D('Gate')->field('id,gate_name as name')->select($ids);
                else
                    $list = array();
                break;
        }
        echo json_encode($list);
    }

    public function get_last_weather(){
        $this->check_login();
        $model = I('get.model')?I('get.model'):false;
        $f_id = I('get.f_id')?I('get.f_id'):false;
        if(!$model){
            echo json_encode(array('status'=>-1, 'msg'=>'pls put parm'));
            exit();
        }
        if(!$f_id){
            echo json_encode(array('msg'=>'不可填报'));
            exit();
        }
        $map['facilities_id'] = array('eq', $f_id);
        switch($model){
            case 'station':
                $map['facilities_type'] = array('eq', 1);
                break;
            case 'csdt':
                $map['facilities_type'] = array('eq', 2);
                break;
            case 'gate':
                $map['facilities_type'] = array('eq', 3);
                break;
        }
        $model = D('WeatherchangeLog');
        $last = $model->where($map)->order('date desc')->find();
        if(!$last){
            echo json_encode(array('msg'=>'雨停了'));
            exit();
        }
        echo json_encode(array('msg'=>weather_status_option($last['rain_sit'], false)));
    }

    public function submit_weather(){
        $this->check_login();
        $data = I('get.')?I('get.'):I('post.');
        $model = D('WeatherchangeLog');
        $data['date'] = getNowTime();
        $uid = I('get.uid')?I('get.uid'):0;
        $data['dutyperson'] = D('MobileAdmin')->get_names_by_ids($uid);
        switch($data['rain_sit']){
            case 1:
                $data['end_time'] = $data['date'];
                break;
            default:
                $data['start_time'] = $data['date'];

                break;
        }
        $new_id = $model->addObj($data);
        if($new_id)
            echo json_encode(array('status'=>$new_id, 'msg'=>'保存成功'));
        else
            echo json_encode(array('status'=>-1, 'msg'=>'保存失败'));
    }

    public function send_fix(){
        $this->check_login();
        if(!I('get.model')){
            echo json_encode(array('status'=>-1, 'msg'=>'pls put parm'));
            exit();
        }
        $data = array();
        $model = D(I('get.model'));
        $data['station'] = I('get.station');
        $infor = $model->get_infor_text(I('get.fy'));
        $data['name'] = $infor['text'];
        $data['content'] = I('get.content');
        $opr = D('MobileAdmin')->queryObj(I('get.uid'), 'id');
        $data['opr'] = $opr['realname'].$opr['phone'];
        $data['phone'] = $infor['phone'];
        $data['report_time'] = getNowTime();
        $fix_model = D('DeviceFix');
        $new_id = $fix_model->add($data);
        if($new_id)
            echo json_encode(array('status'=>$new_id, 'msg'=>'success'));
        else
            echo json_encode(array('status'=>-1, 'msg'=>'eooro'));
    }

    public function check_mobile_version(){
        $version = get_kv_val('mobile_version');
        if($version){
            echo json_encode(array('version'=>$version));
        }else{
            echo json_encode(array('version'=>-1));
        }
    }
    /*******************************获取数据API*******************************/
}